<template>
  <div id="box">
    <h3>{{ id ? '编辑' : '新建'}}物品</h3>
    <el-form label-width="120px" @submit.native.prevent="save">

      <el-form-item label="名称">
        <el-input v-model="model.name"></el-input>
      </el-form-item>
      
      <el-form-item label="图标">
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :headers="getAuthHeaders()"
          :show-file-list="false"
          :on-success="afterUpload"
        >
          <img v-if="model.icon" :src="model.icon" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
          
      <el-form-item>
        <el-button type="primary" native-type="submit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'Item',
  props: {
    id: { type: String }
  },
  data() {
    return {
      model: {},
    }
  },
  methods: {
    afterUpload(res) {
      // Vue 中 显示赋值
      this.$set(this.model, 'icon', res.url);

      // this.model.icon = res.url
    },
    //修改 、 创建列表 
    async save() {
      try {
        let res
        // 修改分类
        if (this.id) {
          res = await this.$http.put(`/rest/items/${this.id}`, this.model);
          this.$message({
            type: 'success',
            message: "修改成功"
          })
        } else {
          // 创建分类
          res = await this.$http.post('/rest/items', this.model);
          this.$message({
            type: 'success',
            message: "创建成功"
          })
        }
        console.log(res);
        this.$router.push('/items/list');
      } catch(err) {
        console.log(err);
      }
    },

    // 获取详情列表（某一个） 
    async fetch() {
      try {
        const res = await this.$http.get(`/rest/items/${this.id}`);
        this.model = res.data
      } catch(err) {
        console.log('修改列表失败');
      }
    }
  },
  created() {
    this.id && this.fetch();
  }
}
</script>

<style>
  
</style>